<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Validator;

use Goods\Entity\GoodsClass;
use Laminas\I18n\Translator\Translator;
use Laminas\Validator\AbstractValidator;

class GoodsClassValidator extends AbstractValidator
{
    const NOT_SCALAR    = 'notScalar';
    const NOT_SELF      = 'notSelf';
    const NOT_SUB       = 'notSub';

    protected $options = [
        'entityManager',
        'goodsClass'
    ];

    protected $messageTemplates = [];

    public function __construct($options = [])
    {
        if(is_array($options)) {
            if(isset($options['entityManager']))    $this->options['entityManager'] = $options['entityManager'];
            if(isset($options['goodsClass']))       $this->options['goodsClass']    = $options['goodsClass'];
        }

        $trans = new Translator();
        $this->messageTemplates = [
            self::NOT_SCALAR => $trans->translate("这不是一个标准输入值"),
            self::NOT_SELF   => $trans->translate("不能为分类本身"),
            self::NOT_SUB    => $trans->translate("不能为自己的下级分类")
        ];

        parent::__construct($options);
    }

    public function isValid($value)
    {
        if(!is_scalar($value)) {
            $this->error(self::NOT_SCALAR);
            return false;
        }

        if($this->options['goodsClass'] == null || $value == 0) return true;

        if($this->options['goodsClass']->getClassId() == $value) {
            $this->error(self::NOT_SELF);
            return false;
        }

        $entityManager  = $this->options['entityManager'];
        $classInfo      = $entityManager->getRepository(GoodsClass::class)->findOneBy(['classId' => $value]);

        $num = strpos($classInfo->getClassPath(), (string) $this->options['goodsClass']->getClassId());
        if($num !== false) {
            $num1 = strpos($classInfo->getClassPath(), (string) $classInfo->getClassId());
            if($num < $num1) {
                $this->error(self::NOT_SUB);
                return false;
            }
        }

        return true;
    }
}